package local.blueheart.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class FilterApple {


    /**
     * 找到所有绿色苹果
     * @param apples 所有苹果
     * @return list
     */
    public static List<Apple> filterGreenApple(List<Apple> apples){
        List<Apple> result = new ArrayList<>();
        for (Apple apple:apples){
            if(apple.getColor().equals("green")){
                result.add(apple);
            }
        }
        return result;
    }

    /**
     * 所有大于150的苹果
     * @param apples
     * @return
     */
    public static List<Apple> filterHeavyApple(List<Apple> apples){
        List<Apple> result = new ArrayList<>();
        for (Apple apple:apples){
            if(apple.getWeight()>150){
                result.add(apple);
            }
        }
        return result;
    }

    //第二种方式，定义一个过滤接口,使用Apple的静态方法
    interface Predicate<T>{
        boolean test(T t);
    }


    /**
     * 使用过滤接口
     * @param apples
     * @param p 测试表达式接口
     * @return
     */
    public static List<Apple> filterApple(List<Apple> apples,Predicate<Apple> p){
        List<Apple> result = new ArrayList<>();
        for (Apple apple:apples){
            if(p.test(apple)){
                result.add(apple);
            }
        }
        return result;
    }





    public static void main(String[] args){
        List<Apple> apples = Arrays.asList(new Apple("green",170),new Apple("yello",150),new Apple("green",140));
        System.out.println(FilterApple.filterGreenApple(apples));
        System.out.println(FilterApple.filterHeavyApple(apples));
        System.out.println("=======使用静态方法(一种特殊的Lamdba表达式)========");
        System.out.println(FilterApple.filterApple(apples,Apple::isGreenApple));
        System.out.println(FilterApple.filterApple(apples,Apple::isHeavyApple));
        System.out.println("=======Lamdbag表达式===========");
        System.out.println(FilterApple.filterApple(apples,apple -> { return "green".equals(apple.getColor());}));
        System.out.println(FilterApple.filterApple(apples,apple -> { return apple.getWeight()>150;}));
        System.out.println("=======更简化的Lamdba表达式=========");
        System.out.println(FilterApple.filterApple(apples,apple -> "green".equals(apple.getColor())));
        System.out.println(FilterApple.filterApple(apples,apple -> apple.getWeight()> 150));
        System.out.println("=======使用Stream=========");
        List<Apple> heavyApples = apples.stream().filter(apple -> apple.getWeight()>150).collect(Collectors.toList());
        List<Apple> heavyApples1 = apples.parallelStream().filter(a -> a.getWeight()>150).collect(Collectors.toList());
        System.out.println(heavyApples);
        System.out.println(heavyApples1);
    }

}
